# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\application\__init__.py
__author__ = "sanyi"
import argparse, os, os.path, yaml, yaml.parser, logging.handlers, logging
from settings_provider import settings
from helpers.application.utils import git_log, adjust_storage_settings, adjust_urls
from helpers.setup_types import *

__logger = logging.getLogger("application.init")


def convert_to_bool(value):
    v = value.lower()
    if v == "true":
        return True
    elif v == "1":
        return True
    else:
        return False


on_premise_ini_file_keys = {
    "uploads_salt",
    "engineonly",
    "target_secret_salt",
    "ssl_ca_bundle_path",
    "logging.file.level",
    "logging.file.file_name",
    "server.host",
    "server.address",
    "server.port",
    "server.static_document_root",
    "server.frontend.api_description",
    "server.frontend.session_secret",
    "server.frontend.host",
    "server.status.api_description",
    "server.ssl.certificate",
    "server.ssl.private_key",
    "storage.targets",
    "storage.scans",
    "storage.reports",
    "storage.license",
    "storage.bxss",
    "storage.updates",
    "base_storage",
    "databases.connections.master.connection.user",
    "databases.connections.master.connection.password",
    "databases.connections.master.connection.host",
    "databases.connections.master.connection.port",
    "databases.connections.master.connection.db",
    "wvs.app_dir",
    "wvs.temp_dir",
    "wvs.debug_mode",
    "pdf_converter",
    "continuous.profile.p1",
    "continuous.profile.p2",
    "app_id",
    "features.multi_sessions_enabled",
}


def override_settings_with_config_file(config_file, allowed_keys):
    for config_line in open(config_file).readlines():
        config_line = config_line.strip()
        try:
            path, value = config_line.split("=", 1)
        except ValueError:
            continue

        if path not in allowed_keys:
            continue
        else:
            if path == "server.port":
                value = int(value)
            else:
                if path == "wvs.debug_mode":
                    value = convert_to_bool(value)
                else:
                    if path == "features.multi_sessions_enabled":
                        value = convert_to_bool(value)
                __logger.debug("Overriding %s", path)
                settings.set(path, value)


def on_premise_init(
    setup_type=ON_PREMISE_MASTER,
    arg_parser_title="WVS application",
    default_settings=None,
):
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("%(asctime)s: %(levelname)s %(name)s %(message)s")
    )
    console_handler.setLevel(logging.DEBUG)
    root_logger.addHandler(console_handler)
    parser = argparse.ArgumentParser(description=arg_parser_title)
    parser.add_argument(
        "--conf",
        dest="config_file",
        default="settings.ini",
        help="config file location",
    )
    args = parser.parse_args()
    if default_settings:
        settings.load(default_settings)
    if not os.path.isfile(args.config_file):
        parser.error("--conf file doesn't exist")
    override_settings_with_config_file(args.config_file, on_premise_ini_file_keys)
    settings.set("setup_type", setup_type)
    console_handler.setLevel(
        getattr(logging, settings.get("logging.console.level", "DEBUG"))
    )
    logging_file_name = settings.get("logging.file.file_name")
    if logging_file_name and settings.get("logging.file.level"):
        file_handler = logging.handlers.TimedRotatingFileHandler(
            logging_file_name, when="midnight", backupCount=5
        )
        file_handler.setFormatter(
            logging.Formatter("%(asctime)s: %(levelname)s %(name)s %(message)s")
        )
        file_handler.setLevel(settings.get("logging.file.level", "DEBUG"))
        root_logger.addHandler(file_handler)
    if not settings.get("logging.console.level"):
        root_logger.removeHandler(console_handler)
    from db import load_sqlalchemy_tables

    load_sqlalchemy_tables()
    git_log()
    adjust_storage_settings()
    adjust_urls()


def init(setup_type, logfile_suffix=None, arg_parser_title="Application"):
    """
    :param setup_type: 
    :param logfile_suffix:
    :param arg_parser_title:
    :return:
    """
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("%(asctime)s: %(levelname)s %(name)s %(message)s")
    )
    console_handler.setLevel(logging.DEBUG)
    root_logger.addHandler(console_handler)
    parser = argparse.ArgumentParser(description=arg_parser_title)
    parser.add_argument(
        "--conf",
        dest="config_file",
        default="settings.yaml",
        help="config file location",
    )
    args = parser.parse_args()
    if not os.path.isfile(args.config_file):
        parser.error("--conf file doesn't exist")
    config_data = None
    config_document = None
    try:
        config_data = open(args.config_file, "rt").read()
    except FileNotFoundError:
        parser.error("--conf file is invalid")
    except Exception:
        parser.error("--conf file is invalid")
        raise

    try:
        config_document = yaml.safe_load(config_data)
    except yaml.parser.ParserError:
        parser.error("--conf file is invalid")

    if config_document is None:
        parser.error("--conf file is invalid")
    settings.load(config_document)
    console_handler.setLevel(
        getattr(logging, settings.get("logging.console.level", "DEBUG"))
    )
    logging_file_name = settings.get("logging.file.file_name")
    if logging_file_name:
        if settings.get("logging.file.level"):
            if logfile_suffix:
                logging_file_name += logfile_suffix
            file_handler = logging.handlers.TimedRotatingFileHandler(
                logging_file_name, when="midnight", backupCount=5, encoding="utf-8"
            )
            file_handler.setFormatter(
                logging.Formatter("%(asctime)s: %(levelname)s %(name)s %(message)s")
            )
            file_handler.setLevel(settings.get("logging.file.level", "DEBUG"))
            root_logger.addHandler(file_handler)
    if not settings.get("logging.console.level"):
        root_logger.removeHandler(console_handler)
    from db import load_sqlalchemy_tables

    load_sqlalchemy_tables()
    git_log()
    settings.set("setup_type", setup_type)
    adjust_storage_settings()
    adjust_urls()
